package com.berchen.schedule;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

/**
 * 动态定时任务 cron表达式可以动态获取
 */
//@Configuration
//@EnableScheduling
public class DynamicSchedule implements SchedulingConfigurer {

    @Value("${cron}")
    private String cron;

    /**
     * 执行定时任务
     * @param scheduledTaskRegistrar
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {

        scheduledTaskRegistrar.addTriggerTask(()->{

            // 定时任务的执行逻辑
            System.out.println("定时任务执行");
        },targerContext->{
            // 动态获取cron表达式 从配置中或者从数据库中拿 动态设置下一个定时任务
            return new CronTrigger(cron).nextExecutionTime(targerContext);
        });
    }
}
